package com.tbq.tbqj_ggl.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;

import com.tbq.tbqj_ggl.utils.AudioHandleUtils;


/**
 * Created by shenjiajun on 2016/4/7.
 */
public class ScratchTextView extends android.support.v7.widget.AppCompatTextView {
    private Bitmap fgBitmap, bgBitmap;// 前景橡皮擦的Bitmap和背景我们底图的Bitmap
    private Paint bgPaint, fgPaint, pathPaint;
    private Path mPath;

    private float lastX, lastY;
    private Rect rect;
    private Bitmap mBitmap;

    private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
    private static final int COLORDRAWABLE_DIMENSION = 2;

    private Canvas mCanvas;
    private Context mContext;

    private OnScratchListent listent;

    public void setOnScratchListent(OnScratchListent listent) {
        this.listent = listent;
    }

    public ScratchTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        onInit();
    }

    public ScratchTextView(Context context) {
        super(context);
        onInit();
    }

    public ScratchTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        onInit();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//        Log.e("onMeasure", "mBitmap width=" + mBitmap.getWidth() + "mBitmap height=" + mBitmap.getHeight());
//        Log.e("onMeasure", "width=" + getMeasuredWidth() + " height=" + getMeasuredHeight());
        rect = new Rect(0, 0, getWidth(), getHeight());
        if (getHeight() > 0 && getWidth() > 0) {
            setUp();
        }
    }

    private void onInit() {
        mPath = new Path();
        pathPaint = new Paint();
        pathPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);

        // 设置画笔透明度为0是关键！我们要让绘制的路径是透明的，然后让该路径与前景的底色混合“抠”出绘制路径
        pathPaint.setARGB(255, 255, 143, 0);

        // 设置混合模式为DST_IN
        pathPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

        // 设置画笔风格为描边
        pathPaint.setStyle(Paint.Style.STROKE);

        // 设置路径结合处样式
        pathPaint.setStrokeJoin(Paint.Join.ROUND);

        // 设置笔触类型
        pathPaint.setStrokeCap(Paint.Cap.ROUND);

        // 设置描边宽度
        pathPaint.setStrokeWidth(30);
    }

    private void setUp() {
        // 生成前景图Bitmap
        fgBitmap = Bitmap.createBitmap(rect.width(), rect.height(), Bitmap.Config.ARGB_8888);

        // 将其注入画布
        mCanvas = new Canvas(fgBitmap);
        // 绘制画布背景为中性灰
        //mCanvas.drawColor(0xFF808080);


        // 定义画笔1
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        // 消除锯齿
        paint.setAntiAlias(true);
        // 设置画笔的颜色
        paint.setColor(0xFF808080);
        // 设置paint的外框宽度
        paint.setStrokeWidth(2);
        mCanvas.drawRect(12, 12, rect.width() - 12, rect.height() - 12, paint);

//        // 获取背景底图Bitmap
//        if (mContext == null) {
//            return;
//        }
//        bgBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.bare_bears);
//
//        // 缩放背景底图Bitmap至屏幕大小
//        bgBitmap = Bitmap.createScaledBitmap(bgBitmap, rect.width(), rect.height(), true);
//        invalidate();
    }

    public void resteData() {
        onInit();
        rect = new Rect(0, 0, getWidth(), getHeight());
        if (getHeight() > 0 && getWidth() > 0) {
            setUp();
        }
        isHd = false;
        isComplete = false;
        postInvalidate();
        //postInvalidate
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (fgBitmap == null) {
            return;
        }

        if (!isComplete) {
            canvas.drawBitmap(fgBitmap, 0, 0, null);
        } else if (isComplete && !isHd) {
            isHd = !isHd;
            if (listent != null) listent.onScratchFull(this);
        }

        pathPaint.setARGB(0, 255, 143, 0);
        mCanvas.drawPath(mPath, pathPaint);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
//        Log.e("onTouchEvent", "x=" + x + "  y=" + y);
//        Log.e("onTouchEvent", "event.getAction()=" + event.getAction());
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //mPath.reset();
                mPath.moveTo(x, y);
                lastX = x;
                lastY = y;
                AudioHandleUtils.getInstance().playMusic("scratchtv.mp3", true);
                listent.onScratchItem(this);
                break;
            case MotionEvent.ACTION_MOVE:
//                Log.e("ActionMove", "x=" + x + "  y=" + y);

                mPath.quadTo(lastX, lastY, x, y);
                lastY = y;
                lastX = x;
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                isScratch = true;
                new Thread(mRunnable).start();
                AudioHandleUtils.getInstance().stopMusic();
                break;
            default:
                break;
        }
        return true;
    }


    /**
     * 统计擦除区域任务
     */
    private boolean isHd;
    private boolean isComplete;
    private int autoCompleteNumber = 50; //自动完成百分比
    private Runnable mRunnable = new Runnable() {
        private int[] mPixels;

        @Override
        public void run() {

            int w = fgBitmap.getWidth();
            int h = fgBitmap.getHeight();

            float wipeArea = 0;
            float totalArea = w * h;

            Bitmap bitmap = fgBitmap;

            mPixels = new int[w * h];

            /**
             * 拿到所有的像素信息
             */
            bitmap.getPixels(mPixels, 0, w, 0, 0, w, h);

            /**
             * 遍历统计擦除的区域
             */
            for (int i = 0; i < w; i++) {
                for (int j = 0; j < h; j++) {
                    int index = i + j * w;
                    if (mPixels[index] == 0) {
                        wipeArea++;
                    }
                }
            }

            /**
             * 根据所占百分比，进行一些操作
             */
            if (wipeArea > 0 && totalArea > 0) {
                int percent = (int) (wipeArea * 100 / totalArea);
         //       L.e("清除区域达到" + percent + "%");

                if (percent > autoCompleteNumber) {
                    Log.e("TAG", "清除区域达到70%，下面自动清除");
                    isComplete = true;
                    postInvalidate();
                }
            }
        }

    };

    public void setComplete(boolean complete) {
        isComplete = complete;
        postInvalidate();
    }

    public void setAutoCompleteNumber(int autoCompleteNumber) {
        this.autoCompleteNumber = autoCompleteNumber;
    }

    public boolean isComplete() {
        return isComplete;
    }

    public interface OnScratchListent {
        public void onScratchFull(ScratchTextView view);
        public void onScratchItem(ScratchTextView view);
    }

    private boolean isScratch = false;

    public boolean isScratch() {
        return isScratch;
    }


}
